﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Draco.Algorithms
{
    public class D_Search
    {
 

        /// <summary>
        /// 二分查找返回对应数据的索引
        /// </summary>
        /// <param name="dateArray">数据数组</param>
        /// <returns>数据的索引</returns>
        public static int BinarySearchIndex(int[] dateArray,int value)
        {
            int length = dateArray.Length;
            IntStruct[] resultStructs = new IntStruct[length];
            for (int i = 0; i < length; i++)
            {
                resultStructs[i].index = i;
                resultStructs[i].value = dateArray[i];
            }
            int result = BinarySearch(resultStructs, value);
            return result;
        }

        //
        private static int BinarySearch(IntStruct[] dataArray, int value)
        {
            int low, high, mid;
            low = 0;
            high = dataArray.Length - 1;
            while (low <= high)
            {
                mid = (low + high) / 2;
                if (dataArray[mid].value == value)
                    return dataArray[mid].index;
                if (dataArray[mid].value > value)
                    high = mid - 1;
                if (dataArray[mid].value < value)
                    low = mid + 1;
            }
            return -1;
        }


        private struct IntStruct
        {
            public int index;
            public int value;
        }

    }
}
